from prj001.models.cc import CC
from prj001.models.cure import Cure
from prj001.models.summary import Summary
from prj001.models.results import Results
from prj001.models.history import History
from prj001.models.relevant import Relevant
# from prj001.models.geninfo import GeneralInfo

from .mobile import date_type

from django.db import transaction


def update_model(info_obj, data):
    # 更新
    info = data.get('info')
    summary = data.get('summary')
    history = data.get('history')
    relevant = data.get('relevant')
    cc = data.get('cc')
    cure = data.get('cure')
    results = data.get('results')

    msg_info = date_type(info)
    msg_history = date_type(history, d_type='history')
    if msg_info or msg_history:
        raise ValueError(msg_history)

    cc_obj = CC.objects.get(person_id=info_obj.id)
    sm_obj = Summary.objects.get(person_id=info_obj.id)
    hs_obj = History.objects.get(person_id=info_obj.id)
    re_obj = Relevant.objects.get(person_id=info_obj.id)
    cu_obj = Cure.objects.get(person_id=info_obj.id)
    rs_obj = Results.objects.get(person_id=info_obj.id)

    import copy
    copy_info = copy.deepcopy(info)
    for key, value in copy_info.items():
        if not value:
            info.pop(key)

    with transaction.atomic(savepoint=True):
        update_point = transaction.savepoint()

        try:
            info_obj.__dict__.update(**info)
            sm_obj.__dict__.update(**summary)
            # history menstruation_is_accompany
            if history.get('menstruation_is_accompany') or history.get('menstruation_is_accompany') == '有':
                history['menstruation_is_accompany'] = True
            else:
                history['menstruation_is_accompany'] = False

            hs_obj.__dict__.update(**history)
            re_obj.__dict__.update(**relevant)
            cc_obj.__dict__.update(**cc)
            cu_obj.__dict__.update(**cure)
            rs_obj.__dict__.update(**results)
            try:
                info_obj.save()
                sm_obj.save()
                hs_obj.save()
                re_obj.save()
                cc_obj.save()
                cu_obj.save()
                rs_obj.save()
            except Exception:
                raise
        except Exception:
            transaction.savepoint_rollback(update_point)
            raise ValueError('信息无法更新')

        transaction.savepoint_commit(update_point)

    return '更新成功'
